package com.wfh.wfhwx.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wfh.wfhwx.common.BaseResponse;
import com.wfh.wfhwx.common.ResultUtils;
import com.wfh.wfhwx.exception.BusinessException;
import com.wfh.wfhwx.exception.ErrorCode;
import com.wfh.wfhwx.exception.ThrowUtils;
import com.wfh.wfhwx.model.dto.WxMaterialQueryRequest;
import com.wfh.wfhwx.model.entity.WxAccount;
import com.wfh.wfhwx.service.WxAccountService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialFileBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialVideoInfoResult;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriUtils;

import java.io.File;
import java.io.InputStream;

/**
 * @author fenghuanwang
 */
@RestController
@RequestMapping("/wx/msg/{appId}")
@Tag(name = "微信消息-供微信调用")
@Slf4j
public class WxMpPortalController {

    private final WxMpService wxMpService = new WxMpServiceImpl();

    @Resource
    private WxAccountService wxAccountService;

    @Resource
    private WxMpMessageRouter messageRouter;

    /**
     * 给微信服务器调用的消息认证接口
     * @param appId
     * @param signature
     * @param nonce
     * @param echostr
     * @param timestamp
     * @return
     */
    @GetMapping(produces = "text/plain;charset=utf-8")
    @Operation(summary = "微信服务器的认证消息", description = "公众号接入开发模式时微信调用此接口")
    public String wxServiceAuth(@PathVariable String appId,
                                @RequestParam(name = "signature") String signature,
                                @RequestParam(name = "nonce") String nonce,
                                @RequestParam(name = "echostr") String echostr,
                                @RequestParam(name = "timestamp") String timestamp) {

        log.info("收到来自微信服务器的认证消息，appId：{}，signature：{}，timestamp：{}，nonce：{}，echostr：{}", appId, signature, timestamp, nonce, echostr);
        // 校验参数完整性
        ThrowUtils.throwIf(StringUtils.isAnyBlank(signature, nonce, echostr, timestamp), ErrorCode.PARAMS_ERROR);
        // 切换到对应的公众号服务
        wxMpService.switchoverTo(appId);
        // 验证签名是否来自微信
        if (wxMpService.checkSignature(timestamp, nonce, signature)) {
            // 设置公众号的认证状态
            wxAccountService.update(Wrappers.lambdaUpdate(WxAccount.class)
                    .eq(WxAccount::getAppId, appId)
                    .set(WxAccount::getVerified, true));
            // 验证成功，返回微信要求的回显的字符串
            return echostr;
        }
        return "非法的请求";
    }

    /**
     * 下载公众号素材
     * @param appId
     * @param mediaId
     * @param fileName
     * @return
     */
    @GetMapping("/img_voice/download")
    @Operation(summary = "下载公众号素材", description = "下载公众号素材")
    public ResponseEntity<InputStreamResource> downloadMaterial(@PathVariable String appId,
                                                              String mediaId,
                                                              String fileName) {
        // 校验参数
        ThrowUtils.throwIf(StringUtils.isAnyBlank(mediaId, fileName), ErrorCode.PARAMS_ERROR);
        // 切换到指定的公众号
        wxMpService.switchoverTo(appId);
        try (InputStream inputStream = wxMpService.getMaterialService().materialImageOrVoiceDownload(mediaId)) {
            // 创建输入流资源
            InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
            // 构建http响应，设置文件的下载头信息
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + UriUtils.encode(fileName, "UTF-8") + "\"")
                    .body(inputStreamResource);

        }catch (Exception e) {
            log.error("下载公众号素材失败，appId：{}，mediaId：{}，fileName：{}", appId, mediaId, fileName, e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "下载公众号素材失败");
        }
    }

    /**
     * 获取视频素材信息
     * @param appId
     * @param materialId
     * @return
     * @throws WxErrorException
     */
    @GetMapping("/{appId}/video/download")
    public BaseResponse<WxMpMaterialVideoInfoResult> getMaterialVideoByMaterial(
            @PathVariable String appId,
            @RequestParam String materialId) throws WxErrorException {
        // 参数校验
        ThrowUtils.throwIf(StringUtils.isAnyBlank(materialId), ErrorCode.PARAMS_ERROR);
        // 切换到指定的公众号
        wxMpService.switchoverTo(appId);
        // 返回视频信息，包含下载链接
        return ResultUtils.success(wxMpService.getMaterialService().materialVideoInfo(materialId));
    }

    /**
     * 查询素材列表接口
     * @param appId
     * @param wxMaterialQueryRequest
     * @return
     * @throws WxErrorException
     */
    @GetMapping("/{appId}/list")
    @Operation(summary = "获取公众号素材列表", description = "获取公众号素材列表")
    public BaseResponse<WxMpMaterialFileBatchGetResult> listAllMaterial(@PathVariable String appId,
                                                                        WxMaterialQueryRequest wxMaterialQueryRequest) throws WxErrorException {
        String materialType = wxMaterialQueryRequest.getMaterialType();
        int current = wxMaterialQueryRequest.getCurrent();
        int size = wxMaterialQueryRequest.getPageSize();
        // 计算偏移量
        int offset = (current - 1) * size;
        // 切换到指定的公众号
        wxMpService.switchoverTo(appId);
        // 调用Wxjava的素材批量获取接口
        return ResultUtils.success(wxMpService.getMaterialService().materialFileBatchGet(materialType, offset, size));
    }

    /**
     * 删除素材
     * @param appId
     * @param materialId
     * @return
     * @throws WxErrorException
     */
    @DeleteMapping("/{appId}/del")
    @Operation(summary = "删除公众号素材")
    public BaseResponse<Boolean> delMaterial(@PathVariable String appId,
                                             @RequestParam String materialId) throws WxErrorException {
        // 校验参数
        ThrowUtils.throwIf(StringUtils.isAnyBlank(materialId), ErrorCode.PARAMS_ERROR);
        // 切换到指定的公众号
        wxMpService.switchoverTo(appId);
        // 调用Wxjava的素材删除接口
        return ResultUtils.success(wxMpService.getMaterialService().materialDelete(materialId));
    }

    /**
     * 处理微信服务器发送来的各种消息
     * @param appId
     * @param requestBody
     * @param signature
     * @param timestamp
     * @param nonce
     * @param openid
     * @param encType
     * @param msgSignature
     * @return
     */
    @PostMapping(produces = "application/xml;charset=UTF-8")
    @Operation(summary = "微信消息处理")
    public String post(
            @PathVariable String appId,
            @RequestBody String requestBody,
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam("openid") String openid,
            @RequestParam(name = "encrypt_type", required = false) String encType,
            @RequestParam(name = "msg_signature", required = false) String msgSignature) {

        // 切换到对应的公众号
        this.wxMpService.switchoverTo(appId);
        // 验证请求签名
        ThrowUtils.throwIf(!wxMpService.checkSignature(timestamp, nonce, signature), ErrorCode.PARAMS_ERROR, "非法请求，可能是伪造的请求");
        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = this.route(appId, inMessage);
            if (outMessage != null) {
                return "";
            }

        } else if ("aes".equals(encType)) {
            // 是aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, this.wxMpService.getWxMpConfigStorage(), timestamp, nonce, msgSignature);
            WxMpXmlOutMessage outMessage = this.route(appId, inMessage);
            if (outMessage != null) {
                return outMessage.toEncryptedXml(this.wxMpService.getWxMpConfigStorage());
            }
            out = outMessage.toEncryptedXml(wxMpService.getWxMpConfigStorage());
        }
        log.info("回复消息是：{}", out);
        return out;

        }
    private WxMpXmlOutMessage route(String appId, WxMpXmlMessage message) {
        try {
            return messageRouter.route(appId, message);
        } catch (Exception e) {
            log.error("路由消息时出现异常", e);
        }
        return null;

    }
    }

